<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
            <!-- <el-form-item label="省" prop="provinceId">
                <el-select v-model="queryParams.provinceId" placeholder="请选择省" @change="chooseProvince" clearable>
                    <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="市" prop="cityId">
                <el-select v-model="queryParams.cityId" placeholder="请选择市" @change="chooseCity" clearable>
                    <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="区/县" prop="areaId">
                <el-select v-model="queryParams.areaId" placeholder="请选择区/县" @change="chooseArea" clearable>
                    <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item> -->
            <el-form-item label="图件名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入图件名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="上传人" prop="uploadUser">
                <el-input v-model="queryParams.uploadUser" placeholder="请输入上传人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="上传日期" style="width: 330px">
                <el-date-picker v-model="uploadTime" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
                    start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item label=" ">
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button plain icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" icon="Plus" @click="otherHandleAdd">上传</el-button>
                <el-button type="primary" @click="handleDelete">删除</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="dataList" stripe @selection-change="handleSelectionChange" row-key="id">
            <el-table-column type="selection" width="55" align="center" reserve-selection />
            <el-table-column label="图件名称" align="center" prop="name">
                <template #default="scope">
                    <el-link type="primary" :underline="false" @click="handleUpdate(scope.row)">{{ scope.row.name }}</el-link>
                </template>
            </el-table-column>
            <el-table-column label="图件类型" align="center" prop="type">
                <template #default="{ row }">
                    <div>
                        {{ chartTypeOption.find(item => item.value == row.type)?.label }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="发震时间" align="center" prop="seismogenicTime" />
            <el-table-column label="震级" align="center" prop="magnitude" />
            <el-table-column label="震中经度" align="center" prop="longitude" />
            <el-table-column label="震中纬度" align="center" prop="latitude" />
            <el-table-column label="上传人" align="center" prop="uploadUser" />
            <el-table-column label="上传日期" align="center" prop="uploadTime" width="180" />
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
            @pagination="getList" />

        <!-- 上传、修改 -->
        <el-dialog :title="otherTitle" v-model="otherShowPopup" width="800px" append-to-body @close="reset">
            <el-form ref="otherRef" :model="otherForm" :rules="otherRules" label-width="120px">
                <el-row class="mt15">
                    <el-col :span="24">
                        <el-form-item label="图件名称" prop="name">
                            <el-input v-model="otherForm.name" placeholder="请输入图件名称" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="图件类型" prop="type">
                            <el-select v-model="otherForm.type" placeholder="请选择图件分类" style="width: 100%;">
                                <el-option v-for="item in chartTypeOption" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="发震时间" prop="seismogenicTime">
                            <el-date-picker v-model="otherForm.seismogenicTime" type="datetime" placeholder="请选择发震时间"
                                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%;"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="震级" prop="magnitude">
                            <el-input v-model="otherForm.magnitude" placeholder="震级" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="震中经度" prop="longitude">
                            <el-input v-model="otherForm.longitude" placeholder="请输入震中经度" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="震中纬度" prop="latitude">
                            <el-input v-model="otherForm.latitude" placeholder="震中纬度" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="图片" prop="mapId">
                            <!--<image-upload ref="otherImgUpload" :fileSize="100" :limit="1" v-model="otherForm.attachList"
                                @uploadSuccess="uploadSuccess" />-->
                            <el-input type="hidden" />
                            <image-upload ref="otherImgUpload" :fileSize="100" :limit="1"  downloadUrl="downLoad"
                                        v-model="otherForm.attachList" @uploadSuccess="uploadSuccess" :show-file-list="false" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="uploadImg" v-show="otherForm.id">下载图件</el-button>
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button plain @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="ChartManger">
import { getPage, uploadSave, getDetailById, uploadUpdate, deleteById, check } from "@/api/resultManag/chartManger";
import { nextTick, reactive } from "vue";
import { saveAs } from 'file-saver'

const { proxy } = getCurrentInstance();
const dataList = ref([]);
const btnType = ref('add')
const otherShowPopup = ref(false);
const otherTitle = ref("");
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const uploadTime = ref("");//提交时间

const data1 = reactive({
    queryParams: {
        page: 1,
        rows: 10,
        taskName: null,
        provinceId: null,
        province: null,
        cityId: null,
        city: null,
        areaId: null,
        area: null,
        uploader: null,
        // uploadTime: null,
        startTime: null,
        endTime: null,
    }
});
const data2 = reactive({
    otherForm: {},
    otherRules: {
        name: [{ required: true, message: "图件名称不能为空", trigger: "blur" }],
        type: [{ required: true, message: "图件类型不能为空", trigger: "change" }],
        seismogenicTime: [{ required: true, message: "发震时间不能为空", trigger: "blur" }],
        magnitude: [{ required: true, message: '震级不能为空', trigger: 'blur' }],
        longitude: [{ required: true, message: '震中经度不能为空', trigger: 'blur' }],
        latitude: [{ required: true, message: '震中纬度不能为空', trigger: 'blur' }],
        mapId: [{ required: true, message: '图件不能为空', trigger: "change" }]
    }
});
const chartTypeOption = ref([
    { label: '基于遥感影像的XX震中影响场范围内房屋抗震能力初判图', value: '0' },
    { label: '建筑物公里格网分布对比图', value: '1' },
    { label: '人口公里格网分布对比图', value: '2' },
    { label: '经济格网分布对比图', value: '3' }
])

const { queryParams } = toRefs(data1);
const { otherForm, otherRules } = toRefs(data2);

function uploadSuccess(file) {
    otherForm.value.mapId = file[0].attachId
    proxy.$refs['otherRef'].validateField('mapId')
}

/** 查询列表 */
function getList() {
    loading.value = true;
    getPage(queryParams.value).then(response => {
        dataList.value = response.data.rows;;
        total.value = response.data.total;
        loading.value = false;
    });
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.page = 1;
    queryParams.value.startTime = uploadTime.value ? uploadTime.value[0] + ' 00:00:00' : "";
    queryParams.value.endTime = uploadTime.value ? uploadTime.value[1] + ' 23:59:59' : "";
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    uploadTime.value = null;
    proxy.resetForm("queryRef");
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id);
}

/** 新增按钮操作 */
function otherHandleAdd() {
    otherShowPopup.value = true;
    otherTitle.value = "图件上传";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    getDetailById(row.id).then(response => {
        otherShowPopup.value = true;
        otherTitle.value = "修改图件信息";
        // nextTick(() => {
            otherForm.value = { 
                ...response.data,
                attachList: [{
                    attachId: response.data.mapId || '', 
                    name: response.data.name || '', 
                    url: import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(response.data.mapId) || ''
                }] 
            }
        // })
    });
}

/*//下载图件
function uploadImg() {
    location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(otherForm.value.mapId);
}*/
//下载图件
function uploadImg() {
  saveAs(otherForm.value.attachList[0].url, '图件')
}

// 取消按钮
function cancel() {
    reset();
    otherShowPopup.value = false;
}

// 表单重置
function reset() {
    otherForm.value.attachList = [];
    proxy.resetForm("otherRef");
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs['otherRef'].validate(valid => {
        otherForm.value.mapId = proxy.$refs["otherImgUpload"].fileList.map(item => item.attachId).join(",");
        if (valid) {
            check(otherForm.value).then(response => {
                if (response.data) {
                    return proxy.$modal.confirm("已有图件，是否覆盖？").then(function () {
                        if(otherForm.value.id) return update();
                        return save();
                    })
                }
                if(otherForm.value.id) return update();
                return save();
            })
        }
    });
}
function save() {
    uploadSave(otherForm.value).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        otherShowPopup.value = false;
        getList();
    });
}
function update() {
    uploadUpdate(otherForm.value).then(() => {
        proxy.$modal.msgSuccess("修改成功");
        otherShowPopup.value = false;
        getList();
    });
}

/** 删除按钮操作 */
function handleDelete() {
    if (!ids.value.length) {
        return proxy.$modal.msgWarning("请选择要删除的数据");
    }
    proxy.$modal.confirm('是否确认删除选中的数据项？').then(function () {
        return deleteById(ids.value);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}

getList();
</script>

<style lang="scss" scoped>
.mt15 {
    margin-top: 15px;
}

.disabled .el-upload--picture-card {
    display: none;
}
</style>
<style lang="scss">
.el-table.chartTable {
    td.el-table__cell {
        border-right: var(--el-table-border) !important;
        border-bottom: var(--el-table-border) !important;
    }

    .el-table__header-wrapper th {
        background-color: #fff !important;
    }
}

.chartForm {
    .borderItem {
        width: 50%;
        border: 1px solid #ebeef5;
        border-bottom: none;
        margin: 0;
        display: inline-block;

        &:nth-child(2n) {
            border-left: none;
        }

        &>.el-row {
            height: 100%;
        }

        .checkboxTd,
        .mapTypeTd,
        .templateTd {
            padding: 15px 10px;
            min-height: 50px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .mapTypeTdContent {
            justify-content: start;
        }

        .checkboxTd,
        .mapTypeTd {
            border-right: 1px solid #ebeef5;
        }

        .templateTd {
            .el-form-item {
                margin: 0;
            }
        }
    }

    .borderItem:last-child,
    .borderItem:nth-last-child(2) {
        border-bottom: 1px solid #ebeef5;
    }
}
</style>
